package user

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/common/cache"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/utils"
	user2 "git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/dto/user"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/remote/modeling_paltform_remote"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/tenant/tenant"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/user"
	"git.myscrm.cn/golang/common/uuid"
	"git.myscrm.cn/golang/stark/v4"
	"strconv"
	"time"
)

const (
	TENANT_INFO_CACHE_KEY            = "gfyx:user_service:tenant_list:"
	TENANT_NAME_CACHE_KEY            = "gfyx:user_service:tenant_name_md5:"
	TENANT_NAME_EMPTY_VALUE          = "empty"
	TENANT_PROFIT_CACHE_KEY          = "gfyx:user_service:tenant_profit:"
	TENANT_PROFIT_CACHE_KEY_TIME_OUT = 60 * 2
)

type UserInfoService struct {
	commonUserDataRepo user.CommonUserDataRepoIface
	userApplyRepo      user.UserApplyRepoIface
	commonUserBindRepo user.CommonUserBindRepoIface
	tenantsRepo        tenant.TenantsRepositoryIface
	tenantsProfitRepo  tenant.TenantsProfitRepositoryIface
}

func NewUserInfoService(
	commonUserDataRepo user.CommonUserDataRepoIface,
	userApplyRepo user.UserApplyRepoIface,
	commonUserBindRepo user.CommonUserBindRepoIface,
	tenantsRepo tenant.TenantsRepositoryIface,
	tenantsProfitRepo tenant.TenantsProfitRepositoryIface,
) UserInfoServiceIface {
	return &UserInfoService{
		commonUserDataRepo: commonUserDataRepo,
		userApplyRepo:      userApplyRepo,
		commonUserBindRepo: commonUserBindRepo,
		tenantsRepo:        tenantsRepo,
		tenantsProfitRepo:  tenantsProfitRepo,
	}
}

// 获取租户权益
func (u *UserInfoService) GetTenantProfitUse(ctx context.Context, tenantCode string) (tenantProfitUse *user2.TenantProfitUse, err error) {
	redisClient, _ := cache.Redis()
	tenantProfitUse = &user2.TenantProfitUse{}
	clueRadarPayStatusHashField := "clue_radar_pay_status"
	tenantProfitCacheKey := TENANT_PROFIT_CACHE_KEY + tenantCode
	clueRadarPayStatus, err := redisClient.HGet(ctx, tenantProfitCacheKey, clueRadarPayStatusHashField)
	if err != nil {
		stark.Logger.Errorf(ctx, "读取 %s 租户权益缓存失败,err:%+v", tenantCode, err)
		return tenantProfitUse, err
	}
	temp, _ := strconv.Atoi(clueRadarPayStatus)
	tenantProfitUse.ClueRadarPayStatus = int64(temp)
	if tenantProfitUse.ClueRadarPayStatus != 0 {
		return tenantProfitUse, nil
	}
	// 获取租户的权益总数
	tenantProfitCount, err := u.tenantsProfitRepo.GetTenantProfitCount(ctx, tenantCode)
	if tenantProfitCount == 0 {
		// 注意：数据库没有任何租户的权益信息时，认为是已付费，防止没同步数据的情况造成用户使用不了
		tenantProfitUse.ClueRadarPayStatus = constants.TenantProfit_ClueRadarPayStatus_Paid
	} else {
		// 获取线索雷达权益
		commonTenantProfitList, err := u.tenantsProfitRepo.GetTenantClueRadarProfitList(ctx, tenantCode)
		if err != nil {
			return tenantProfitUse, err
		}
		if len(commonTenantProfitList) <= 0 {
			tenantProfitUse.ClueRadarPayStatus = constants.TenantProfit_ClueRadarPayStatus_Unpaid
		} else {
			if time.Now().After(commonTenantProfitList[0].EndTime.Time) {
				tenantProfitUse.ClueRadarPayStatus = constants.TenantProfit_ClueRadarPayStatus_Unpaid
			} else {
				tenantProfitUse.ClueRadarPayStatus = constants.TenantProfit_ClueRadarPayStatus_Paid
			}
		}

		// 设置缓存
		_, err = redisClient.HSet(ctx, tenantProfitCacheKey, clueRadarPayStatusHashField, tenantProfitUse.ClueRadarPayStatus)
		if err != nil {
			stark.Logger.Errorf(ctx, "set %s 租户权益缓存失败,err:%+v", tenantCode, err)
			return tenantProfitUse, err
		}
		_, err = redisClient.Expire(ctx, tenantProfitCacheKey, TENANT_PROFIT_CACHE_KEY_TIME_OUT)
		if err != nil {
			stark.Logger.Errorf(ctx, "set租户权益缓存有效期失败，cache_key:%s,err:%+v", tenantProfitCacheKey, err)
		}
	}
	return tenantProfitUse, nil
}

// SaveUserApply
// 保存用户申请信息
func (u *UserInfoService) SaveUserApply(ctx context.Context, userApply *user.CommonUserApply) (*user.CommonUserApply, error) {
	return u.userApplyRepo.SaveUserApply(ctx, userApply)
}

func (u *UserInfoService) GetUserInfo(ctx context.Context, paramType int32, param string) (*user.CommonUserInfoBo, error) {
	condition := make(map[string]interface{})
	switch paramType {
	case 1:
		condition["common_user_bind.mp_openid"] = param
	case 2:
		condition["common_user_data.uid"] = param
	case 3:
		condition["common_user_data.mobile_phone"] = param
	case 4:
		condition["common_user_bind.openid"] = param
	}
	if len(condition) == 0 {
		return nil, errors.New("paramType 类型错误")
	}

	commonUserInfoBo, err := u.commonUserDataRepo.GetInfoLeftJoinBind(ctx, condition)
	if err != nil {
		return nil, err
	}
	tenantName, err := u.GetTenantName(ctx, commonUserInfoBo.TenantCode, false)
	if err != nil {
		return nil, err
	}
	commonUserInfoBo.TenantName = tenantName
	return commonUserInfoBo, nil
}

func (u *UserInfoService) BatchSaveUserRoleRelation(ctx context.Context, tenantCode string, user2RoleList []modeling_platfrom_remote.User2RoleList) (bool, error) {
	//添加事务？
	condition := map[string]interface{}{}
	condition["tenant_code"] = tenantCode
	conditionGetUserList := map[string]interface{}{}
	conditionGetUserList["tenant_code"] = tenantCode
	conditionGetUserList["is_deleted"] = 0
	_, commonUserList, err := u.commonUserDataRepo.GetList(ctx, condition, 0, 5000, "")
	if err != nil {
		return false, err
	}

	db := stark.MySQLConn.Get(ctx)
	db = db.Begin()
	// 先删后插入
	err = u.commonUserDataRepo.DelUserRoleRelation(ctx, db, tenantCode)
	if err != nil {
		stark.Logger.Warn(ctx, "用户角色关系删除出错，租户code："+tenantCode+" "+err.Error())
		db.Rollback()
		return false, err
	}
	dbCommonUserRoleRelation := []*user.CommonUserRoleRelation{}
	for _, user2Role := range user2RoleList {
		commonUserDataUid := ""
		for _, commonUser := range commonUserList {
			// 存在数据库
			if user2Role.UserID == commonUser.TenantUserUid {
				commonUserDataUid = user2Role.UserID
				break
			}
		}
		if commonUserDataUid == "" {
			stark.Logger.Warn(ctx, "用户角色关系保存跳过，用户不存在数据库中，租户code："+tenantCode+",用户id："+user2Role.UserID)
			continue
		}
		dbCommonUserRoleRelation = append(dbCommonUserRoleRelation, &user.CommonUserRoleRelation{
			Uid:               uuid.GetUUID(),
			CommonUserDataUid: commonUserDataUid,
			RefType:           user2Role.RefType,
			RoleUid:           user2Role.RoleID,
			TenantCode:        tenantCode,
			TenantUserUid:     user2Role.UserID,
			CreatedTime:       time.Now(),
		})
	}
	err = u.commonUserDataRepo.CreateUserRoleRelation(ctx, db, dbCommonUserRoleRelation)
	if err != nil {
		db.Rollback()
		stark.Logger.Warn(ctx, "用户角色关系写入出错，租户code："+tenantCode+" "+err.Error())
		return false, err
	}
	err = db.Commit().Error
	if err != nil {
		stark.Logger.Warn(ctx, "用户角色关系写入commit出错", err.Error())
		return false, err
	}
	return true, nil

	//
	//
	//for _, info := range user2RoleList {
	//	if info.UserID == "" {
	//		stark.Logger.Warn(ctx, "过滤用户id为空的用户角色关系信息，租户code：", tenantCode, ",用户信息: %+v", info)
	//		continue
	//	}
	//	if info.RoleID == "" {
	//		stark.Logger.Warn(ctx, "过滤角色id为空的用户角色关系信息，租户code：", tenantCode, ",用户id：", info.RoleID)
	//		continue
	//	}
	//	conditionGetUserInfo := map[string]interface{}{
	//		"tenant_code": tenantCode,
	//		"tenant_user_uid": info.UserID,
	//	}
	//	userData, err := u.commonUserDataRepo.GetUserIno(ctx, conditionGetUserInfo)
	//	if err != nil {
	//		return false, err
	//	}
	//	condition[""]
	//	userData, err := u.commonUserDataRepo.GetUserRoleRelation(ctx, condition)
	//	if err != nil {
	//		return false, err
	//	}
	//	if userData != nil {
	//		//update
	//		updateData := map[string]interface{}{
	//			"user_name":     info.UserName,
	//			"user_code":     info.UserCode,
	//			"mobile_phone":  info.MobilePhone,
	//			"is_disable":    info.IsDisable,
	//			"modified_time": time.Now(),
	//			"is_deleted":    0,
	//		}
	//		updateCondition := map[string]interface{}{
	//			"uid": userData.Uid,
	//		}
	//
	//		flag, err := u.commonUserDataRepo.Update(ctx, updateData, updateCondition)
	//		if err != nil {
	//			stark.Logger.Warn(ctx, "用户更新出错，租户code："+tenantCode+",用户id："+info.UserId)
	//			return false, err
	//		}
	//		if flag == false {
	//			stark.Logger.Warn(ctx, "用户更新失败，租户code："+tenantCode+",用户id："+info.UserId)
	//			return false, nil
	//		}
	//	} else {
	//		//insert
	//		isDisable := 0
	//		if info.IsDisable == true {
	//			isDisable = 1
	//		}
	//		commonUserData := &user.CommonUserData{}
	//		commonUserData.Uid = uuid.GetUUID()
	//		commonUserData.TenantCode = tenantCode
	//		commonUserData.TenantUserUid = info.UserId
	//		commonUserData.UserName = info.UserName
	//		commonUserData.UserCode = info.UserCode
	//		commonUserData.MobilePhone = info.MobilePhone
	//		commonUserData.IsDisable = int32(isDisable)
	//
	//		flag, err := u.commonUserDataRepo.Insert(ctx, commonUserData)
	//		if err != nil {
	//			stark.Logger.Warn(ctx, "用户写入出错，租户code："+tenantCode+",用户id："+info.UserId)
	//			return false, err
	//		}
	//		if flag == false {
	//			stark.Logger.Warn(ctx, "用户写入失败，租户code："+tenantCode+",用户id："+info.UserId)
	//			return false, nil
	//		}
	//	}
	//}
	//return true, nil
}

func (u *UserInfoService) BatchSaveUserInfo(ctx context.Context, tenantCode string, userList []modeling_platfrom_remote.UserInfo) (bool, error) {
	//添加事务？
	condition := map[string]interface{}{}
	condition["tenant_code"] = tenantCode
	for _, info := range userList {
		if info.UserGuid == "" {
			stark.Logger.Warn(ctx, "过滤用户id为空的用户信息，租户code：", tenantCode, ",用户信息: %+v", info)
			continue
		}
		if info.MobilePhone == "" {
			stark.Logger.Warn(ctx, "过滤手机号为空的用户信息，租户code：", tenantCode, ",用户id：", info.UserGuid)
			continue
		}
		condition["tenant_user_uid"] = info.UserGuid
		condition["is_deleted"] = 0
		userData, err := u.commonUserDataRepo.GetUserIno(ctx, condition)
		if err != nil {
			return false, err
		}
		isDisable := 0
		if info.IsDisable == true {
			isDisable = 1
		}
		// 待更新或插入的用户结构体
		commonUserData := &user.CommonUserData{
			TenantUserId: info.UserId,
		}
		commonUserData.TenantCode = tenantCode
		commonUserData.TenantUserUid = info.UserGuid
		commonUserData.UserName = info.UserName
		commonUserData.UserCode = info.UserCode
		commonUserData.MobilePhone = info.MobilePhone
		commonUserData.IsDisable = int32(isDisable)
		commonUserData.BuUid = info.BuGuid
		commonUserData.Password = info.Password
		if userData != nil {
			commonUserData.Uid = userData.Uid
			//update
			updateData := map[string]interface{}{
				"user_name":     info.UserName,
				"mobile_phone":  info.MobilePhone,
				"is_disable":    info.IsDisable,
				"modified_time": time.Now(),
				"is_deleted":    0,
			}
			if info.UserCode != "" {
				updateData["user_code"] = info.UserCode
			}
			if info.BuGuid != "" {
				updateData["bu_uid"] = info.BuGuid
			}
			if info.Password != "" {
				updateData["password"] = info.Password
			}
			if info.UserId != 0 {
				updateData["tenant_user_id"] = info.UserId
			}
			updateCondition := map[string]interface{}{
				"uid": userData.Uid,
			}

			flag, err := u.commonUserDataRepo.Update(ctx, updateData, updateCondition)
			if err != nil {
				stark.Logger.Error(ctx, "用户更新出错，租户code："+tenantCode+",用户id："+info.UserGuid)
				return false, err
			}
			if flag == false {
				stark.Logger.Error(ctx, "用户更新失败，租户code："+tenantCode+",用户id："+info.UserGuid)
				return false, nil
			}
			// 修改模式下个人转租户/或更换mpopenid绑定关系逻辑处理
			err = u.PersonalUserToTenantOrChangeMpopenidRelationFromUpdate(ctx, info.MobilePhone, userData, commonUserData)
			if err != nil {
				stark.Logger.Error(ctx, "用户同步修改模式下个人转租户/或更换mpopenid绑定关系逻辑处理报错：", "userData:", userData, "commonUserData:", commonUserData)
				return false, err
			}

		} else {
			//insert
			commonUserData.Uid = uuid.GetUUID()
			// 个人转租户判断
			isPersonalUserToTenant, personalUserData, err := u.IsPersonalUserToTenant(ctx, commonUserData.MobilePhone)
			if err != nil {
				return false, err
			}
			if isPersonalUserToTenant == true {
				err := u.PersonalUserToTenant(ctx, personalUserData, commonUserData)
				if err != nil {
					stark.Logger.Error(ctx, "用户同步创建模式个人转租户报错：", "personalUserData:", personalUserData, "commonUserData:", commonUserData)
					return false, err
				}
			} else {
				flag, err := u.commonUserDataRepo.Insert(ctx, commonUserData)
				if err != nil {
					stark.Logger.Warn(ctx, "用户写入出错，租户code："+tenantCode+",用户id："+info.UserGuid)
					return false, err
				}
				if flag == false {
					stark.Logger.Warn(ctx, "用户写入失败，租户code："+tenantCode+",用户id："+info.UserGuid)
					return false, nil
				}
				// 新增用户模式下更换mpopenid绑定关系逻辑处理
				err = u.changeMpopenidRelationFromInsert(ctx, commonUserData)
				if err != nil {
					stark.Logger.Error(ctx, "新增用户模式下更换mpopenid绑定关系逻辑处理报错：err:"+err.Error())
					return false, err
				}
			}
		}
	}
	return true, nil
}

// 新增用户模式下更换mpopenid绑定关系逻辑处理
func (u *UserInfoService) changeMpopenidRelationFromInsert(ctx context.Context, commonUserData *user.CommonUserData) error {
	// 通过手机号获取最新openid绑定关系
	lastUserBind, err := u.commonUserBindRepo.GetLastBindByMobile(ctx, commonUserData.MobilePhone, "")
	if err != nil {
		return err
	}
	if lastUserBind.CommonUserDataUid == "" {
		// 无需处理
		return nil
	}
	// mpopenid与用户id绑定关系是最新的，则无需修改绑定关系(创建用户的流程上，逻辑上不存在最新绑定关系)
	if commonUserData.Uid == lastUserBind.CommonUserDataUid {
		// 无需处理
		return nil
	}
	stark.Logger.Infof(ctx, "进入新增用户模式下更换mpopenid绑定关系逻辑处理, commonUserData:%+v", commonUserData)

	// 创建最新mpopenid与用户绑定关系
	err = u.bindMpOpenids(ctx, lastUserBind.CommonUserDataUid, commonUserData.Uid, commonUserData.TenantUserUid)
	if err != nil {
		return err
	}

	return nil
}

// 修改模式下个人转租户/或更换mpopenid绑定关系逻辑处理
func (u *UserInfoService) PersonalUserToTenantOrChangeMpopenidRelationFromUpdate(ctx context.Context, updateMobile string, updateBeforeUserData *user.CommonUserData, updateUserData *user.CommonUserData) error {
	// 通过手机号获取最新openid绑定关系
	lastUserBind, err := u.commonUserBindRepo.GetLastBindByMobile(ctx, updateMobile, "")
	if err != nil {
		return err
	}
	if lastUserBind.CommonUserDataUid == "" {
		// 无需处理
		return nil
	}
	// mpopenid与用户id绑定关系是最新的，且手机号没做变更，则无需修改用户绑定关系
	if updateUserData.Uid == lastUserBind.CommonUserDataUid && updateMobile == updateBeforeUserData.MobilePhone {
		// 无需处理
		return nil
	}
	stark.Logger.Infof(ctx, "进入 修改模式下个人转租户/或更换mpopenid绑定关系逻辑处理, updateMobile:%s, updateBeforeUserData:%+v, updateUserData:%+v", updateMobile, updateBeforeUserData, updateUserData)

	// 手机号变更时...
	if updateMobile != updateBeforeUserData.MobilePhone {
		stark.Logger.Info(ctx, "修改模式下手机号变更时逻辑处理...")
		// 查询这个手机号是否存在没有租户的用户
		condition := make(map[string]interface{})
		condition["mobile_phone"] = updateMobile
		condition["tenant_code"] = ""
		personalUserData, err := u.commonUserDataRepo.GetInfo(ctx, condition, "modified_time desc")
		if err != nil {
			return err
		}
		// 这个手机号存在没租户的用户
		if personalUserData.MobilePhone != "" {
			//stark.Logger.Info(ctx, "修改模式下个人转租户触发处理 PersonalUserToTenantOrChangeMpopenidRelationFromUpdate PersonalUserToTenant ","personalUserData:", personalUserData, "updateUserData", updateBeforeUserData)
			//// 合并用户+个人转租户处理
			//err = u.PersonalUserToTenant(ctx, personalUserData, updateUserData)
			//if err != nil {
			//	return err
			//}

			//修改模式下，个人用户转租户逻辑，这个操作会存在用户合并问题，目前是删除掉个人用户
			stark.Logger.Info(ctx, "修改模式下存在没租户的用户，把个人用户删除，且更新绑定关系", "personalUserData:", personalUserData, "updateUserData", updateBeforeUserData)
			// 删除个人用户
			conditionDel := make(map[string]interface{})
			conditionDel["uid"] = personalUserData.Uid
			_, _ = u.commonUserDataRepo.Delete(ctx, conditionDel)
			// 创建最新mpopenid与用户绑定关系
			err := u.bindMpOpenids(ctx, lastUserBind.CommonUserDataUid, updateUserData.Uid, updateUserData.TenantUserUid)
			if err != nil {
				return err
			}

		} else {
			// 手机号变更，且mpopenid与用户id绑定关系不是最新时...更新最新openid绑定关系
			// 存在最新openid绑定关系,拿到用户id
			stark.Logger.Info(ctx, "修改模式下手机号有变更，且mpopenid与用户id绑定关系不是最新时处理（更新最新mpopenid绑定关系）")
			// 创建最新mpopenid与用户绑定关系
			err := u.bindMpOpenids(ctx, lastUserBind.CommonUserDataUid, updateUserData.Uid, updateUserData.TenantUserUid)
			if err != nil {
				return err
			}
		}
	} else {
		// 手机号没变更，但是mpopenid与用户id绑定关系不是最新时...更新最新openid绑定关系
		// 存在最新openid绑定关系,拿到用户id
		stark.Logger.Info(ctx, "修改模式下手机号没变更，但是mpopenid与用户id绑定关系不是最新时处理（更新最新mpopenid绑定关系）")
		// 创建最新mpopenid与用户绑定关系
		err := u.bindMpOpenids(ctx, lastUserBind.CommonUserDataUid, updateUserData.Uid, updateUserData.TenantUserUid)
		if err != nil {
			return err
		}
	}

	return nil
}

// 创建最新用户和openid的绑定关系
func (u *UserInfoService) bindMpOpenids(ctx context.Context, lastUserBindCommonUserDataUid string, commonUserDataUid string, tenantUserUid string) error {
	// 查询最新绑定用户id在绑定表中的所有去重记录
	mpOpenids, err := u.commonUserBindRepo.GetDistinctMpOpenidsByCommonUserId(ctx, lastUserBindCommonUserDataUid)
	if err != nil {
		return err
	}
	if len(mpOpenids) > 0 {
		// 创建最新用户和openid的绑定关系
		err := u.commonUserBindRepo.BindMpOpenids(ctx, commonUserDataUid, tenantUserUid, mpOpenids)
		if err != nil {
			return err
		}
	}
	return nil
}

// 个人转租户
func (u *UserInfoService) PersonalUserToTenant(ctx context.Context, personalUserData *user.CommonUserData, tenantUserData *user.CommonUserData) error {
	personalUserData.TenantCode = tenantUserData.TenantCode
	updateCondition := make(map[string]interface{})
	updateCondition["uid"] = personalUserData.Uid
	updateData := map[string]interface{}{
		"tenant_code":     personalUserData.TenantCode,
		"tenant_user_uid": tenantUserData.TenantUserUid,
		"user_name":       tenantUserData.UserName,
		"user_code":       tenantUserData.UserCode,
		"bu_uid":          tenantUserData.BuUid,
		"password":        tenantUserData.Password,
		"modified_time":   time.Now(),
	}
	_, err := u.commonUserDataRepo.Update(ctx, updateData, updateCondition)
	if err != nil {
		stark.Logger.Error(ctx, "PersonalUserToTenant Update err "+err.Error()+"uid:"+personalUserData.Uid)
		return err
	}
	commonPersonalUserToTenantRecordPo := &user.CommonPersonalUserToTenantRecordPo{
		MobilePhone:       personalUserData.MobilePhone,
		TenantCode:        tenantUserData.TenantCode,
		CommonUserDataUid: personalUserData.Uid,
		TenantUserUid:     tenantUserData.TenantUserUid,
		CreatedTime:       time.Now(),
	}
	err = u.commonUserDataRepo.PersonalUserToTenantRecordWrite(ctx, commonPersonalUserToTenantRecordPo)
	if err != nil {
		stark.Logger.Error(ctx, "PersonalUserToTenant PersonalUserToTenantRecordWrite err "+err.Error()+"uid:"+personalUserData.Uid)
		return err
	}
	// 小程序绑定表刷新租户用户id
	updateData = map[string]interface{}{
		"tenant_user_uid": tenantUserData.TenantUserUid,
		"created_time":    time.Now(),
		"modified_time":   time.Now(),
	}
	updateCondition = map[string]interface{}{
		"common_user_data_uid": personalUserData.Uid,
		"tenant_user_uid":      "",
	}
	_, err = u.commonUserBindRepo.Update(ctx, updateData, updateCondition)
	return nil
}

// 判断是否是个人转租户
func (u *UserInfoService) IsPersonalUserToTenant(ctx context.Context, mobile string) (bool, *user.CommonUserData, error) {
	// 查询手机号是否存在，存在则走经销商（个人用户）转租户逻辑
	condition := make(map[string]interface{})
	condition["mobile_phone"] = mobile
	condition["tenant_code"] = ""
	commonUserData, err := u.commonUserDataRepo.GetInfo(ctx, condition, "modified_time desc")
	if err != nil {
		return false, nil, err
	}
	if commonUserData == nil || commonUserData.MobilePhone == "" {
		return false, commonUserData, nil
	}
	// 核实是个人转租户
	return true, commonUserData, nil
}

func (u *UserInfoService) BatchSaveUserActionRightInfos(ctx context.Context, tenantCode string, tenantUserUid string, userActionRightInfos []*modeling_platfrom_remote.UserActionRightInfos) (bool, error) {
	//condition := map[string]interface{}{}
	//condition["tenant_code"] = tenantCode
	//condition["tenant_user_uid"] = tenantCode
	//dbUserActionRightInfos, err := u.commonUserDataRepo.GetUserActionRightInfos(ctx, condition)
	//if err != nil {
	//	return false, err
	//}
	db := stark.MySQLConn.Get(ctx)
	db = db.Begin()
	// 先删后插入
	err := u.commonUserDataRepo.DelUserActionRightInfos(ctx, db, tenantCode, tenantUserUid)
	if err != nil {
		stark.Logger.Warn(ctx, "用户权限删除出错，租户code："+tenantCode+",用户id："+tenantUserUid, err.Error())
		db.Rollback()
		return false, err
	}
	dbUserActionRightInfos := []*user.CommonUserActionRightInfos{}
	for _, userActionRightInfo := range userActionRightInfos {
		dbUserActionRightInfos = append(dbUserActionRightInfos, &user.CommonUserActionRightInfos{
			Uid:           uuid.GetUUID(),
			FunctionCode:  userActionRightInfo.FunctionCode,
			ActionCode:    userActionRightInfo.ActionCode,
			Application:   userActionRightInfo.Application,
			TenantCode:    tenantCode,
			TenantUserUid: tenantUserUid,
			CreatedTime:   time.Now(),
		})
	}
	err = u.commonUserDataRepo.CreateUserActionRightInfos(ctx, db, dbUserActionRightInfos)
	if err != nil {
		db.Rollback()
		stark.Logger.Warn(ctx, "用户权限写入出错，租户code："+tenantCode+",用户id："+tenantUserUid, err.Error())
		return false, err
	}
	err = db.Commit().Error
	if err != nil {
		stark.Logger.Warn(ctx, "用户权限写入commit出错", err.Error())
		return false, err
	}
	return true, nil
}

func (u *UserInfoService) IncrSyncUser(ctx context.Context, tenantCode, operation string, userList []modeling_platfrom_remote.UserInfo) (bool, error) {
	if operation == "I" || operation == "U" {
		flag, err := u.BatchSaveUserInfo(ctx, tenantCode, userList)
		if err != nil {
			return false, err
		}
		if flag == false {
			return false, errors.New("用户保存失败，租户code：" + tenantCode)
		}
	} else if operation == "D" {
		condition := map[string]interface{}{}
		for _, info := range userList {
			condition["tenant_user_uid"] = info.UserGuid
			condition["tenant_code"] = tenantCode
			_, _ = u.commonUserDataRepo.Delete(ctx, condition)
			// 删除绑定表(应该不存在不同租户tenant_user_uid重复的情况吧，目前绑定表没区分租户)
			conditionDelete := map[string]interface{}{
				"tenant_user_uid": info.UserGuid,
			}
			_, _ = u.commonUserBindRepo.Delete(ctx, conditionDelete)
		}
	}

	return false, nil
}

// 获取租户名
func (u *UserInfoService) GetTenantName(ctx context.Context, tenantCode string, isClean bool) (string, error) {
	if tenantCode == "mysoft" {
		return "MySoft", nil
	}
	cacheKey := TENANT_INFO_CACHE_KEY + tenantCode
	redisClient, _ := cache.Redis()
	//redisClient.Do(ctx,"GET", cacheKey)
	if isClean == false {
		//获取缓存
		tenantNamme, err := redisClient.HGet(ctx, cacheKey, "name")
		if err != nil {
			stark.Logger.Errorf(ctx, "读取 %s 租户缓存失败,err:%+v", tenantCode, err)
			return "", err
		}
		if tenantNamme != "" {
			return tenantNamme, nil
		}
	}

	tenantList, err := u.updateTenantListCache(ctx)
	if err != nil {
		return "", err
	}
	if tenantList == nil {
		return "", errors.New("租户列表为空")
	}
	tenantName := ""
	for _, info := range tenantList {
		if info.Code == tenantCode {
			tenantName = info.Name
		}
	}

	return tenantName, nil
}

func (u *UserInfoService) GetTenantCodeByName(ctx context.Context, companyName string) (string, error) {
	cacheKey := TENANT_NAME_CACHE_KEY + utils.Md5(companyName)
	redisClient, err := cache.Redis()
	if err != nil {
		return "", err
	}
	//获取缓存
	tenantCode, err := redisClient.Get(ctx, cacheKey)
	if err != nil {
		stark.Logger.Errorf(ctx, "读取 %s 租户缓存失败,err:%+v", cacheKey, err)
		return "", err
	}
	if tenantCode == "" {
		// 租户不存在，更新缓存
		_, _ = u.updateTenantListCache(ctx)
		// 二次读取获取
		tenantCode, err = redisClient.Get(ctx, cacheKey)
		if err != nil {
			stark.Logger.Errorf(ctx, "读取 %s 租户缓存失败,err:%+v", cacheKey, err)
			return "", err
		}
		if tenantCode == "" {
			// 公司名还是不存在，说明该公司不是租户，设置一个缓存的默认空值，避免每次都调用接口
			_, err = redisClient.Set(ctx, cacheKey, TENANT_NAME_EMPTY_VALUE, true, 86400)
		}
	}
	// 设置的默认空值，吞掉
	if tenantCode == TENANT_NAME_EMPTY_VALUE {
		tenantCode = ""
	}

	return tenantCode, nil
}

func (u *UserInfoService) updateTenantListCache(ctx context.Context) ([]*tenant.Tenants, error) {
	redisClient, _ := cache.Redis()
	tenantList, err := u.tenantsRepo.GetAllTenant(ctx)
	if err != nil {
		return nil, err
	}
	if tenantList == nil {
		return nil, errors.New("租户列表为空")
	}
	for _, info := range tenantList {
		cacheKey := TENANT_INFO_CACHE_KEY + info.Code
		_, err := redisClient.HSet(ctx, cacheKey, "name", info.Name)
		//根据需求添加租户其他信息的缓存
		if err != nil {
			stark.Logger.Errorf(ctx, "set %s 租户缓存失败,err:%+v", info.Code, err)
			return nil, err
		}

		cacheKey2 := TENANT_NAME_CACHE_KEY + utils.Md5(info.Name)
		_, err = redisClient.Set(ctx, cacheKey2, info.Code, true, 86400)
		//根据需求添加租户其他信息的缓存
		if err != nil {
			stark.Logger.Errorf(ctx, "set %s 租户id:%s 缓存失败,err:%+v", cacheKey2, info.Code, err)
			return nil, err
		}
		_, err = redisClient.Expire(ctx, cacheKey, 86400)
		if err != nil {
			stark.Logger.Errorf(ctx, "set缓存有效期失败，cache_key:%s,err:%+v", cacheKey, err)
		}
	}

	return tenantList, nil
}
